package com.xmtlxx.web.controller.wms.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.xmtlxx.web.controller.wms.service.IExWarehouseService;
import com.xmtlxx.common.annotation.Log;
import com.xmtlxx.common.annotation.RepeatSubmit;
import com.xmtlxx.common.core.controller.BaseController;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.R;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.core.validate.AddGroup;
import com.xmtlxx.common.core.validate.EditGroup;
import com.xmtlxx.common.core.validate.QueryGroup;
import com.xmtlxx.common.enums.BusinessType;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.common.utils.poi.ExcelUtil;
import com.xmtlxx.oms.domain.bo.ContactsBo;
import com.xmtlxx.oms.domain.vo.ContactsVo;
import com.xmtlxx.oms.service.IContactsService;
import com.xmtlxx.system.domain.bo.SysOssBo;
import com.xmtlxx.system.service.ISysOssService;
import com.xmtlxx.wms.domain.bo.ExWarehouseBo;
import com.xmtlxx.wms.domain.bo.ExWarehouseDtlBo;
import com.xmtlxx.wms.domain.bo.ExWarehouseProExportBo;
import com.xmtlxx.wms.domain.vo.ExWarehouseDtlVo;
import com.xmtlxx.wms.domain.vo.ExWarehouseProExportVo;
import com.xmtlxx.wms.domain.vo.ExWarehouseVo;
import com.xmtlxx.wms.domain.vo.InventoryPlanProExportVo;
import com.xmtlxx.wms.service.IExWarehouseDtlService;
import com.xmtlxx.wms.service.IStoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;

/**
 * 出库单Controller
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Validated
@Api(value = "出库单控制器", tags = {"出库单管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/wms/exWarehouse")
public class ExWarehouseController extends BaseController {

    private final IExWarehouseService iExWarehouseService;

    private final IExWarehouseDtlService iExWarehouseDtlService;

    private final IStoreService iStoreService;

    private final IContactsService iContactsService;

    private final ISysOssService iSysOssService;

    /**
     * 返回一个初始化的对象到前端，方便进行动态渲染
     */
    @ApiOperation("用于返回一个初始化对象")
    @PostMapping("/initBean")
    R<ExWarehouseVo> initBean(){
        ExWarehouseVo vo = new ExWarehouseVo();
        vo.setDeptId(LoginHelper.getDeptId());

        ContactsVo contactsVo = null;
        ContactsBo contactsBo = new ContactsBo();
        contactsBo.setDeptId(LoginHelper.getDeptId());
        List<ContactsVo> contactsVos = iContactsService.queryList(contactsBo);
        //获取联系人信息
        if(contactsVos != null && contactsVos.size() > 0){
            for (ContactsVo contacts:contactsVos){
                if(StringUtils.isNotEmpty(contacts.getFlag()) && contacts.getFlag().equals("Y")){
                    contactsVo = contacts;
                    break;
                }
            }
            if(ObjectUtil.isNull(contactsVo)){
                contactsVo = contactsVos.get(0);
            }
        }
        if(ObjectUtil.isNotNull(contactsVo)){
            vo.setContacts(contactsVo.getName());
            vo.setTel(contactsVo.getTel());
            vo.setAddress(contactsVo.getAddress());
        }
        //可以对数据进行初始化
        return R.ok(vo);
    }

    /**
     * 查询出库单列表
     */
    @ApiOperation("查询出库单列表")
//    @SaCheckPermission("wms:exWarehouse:list")
    @GetMapping("/list")
    public TableDataInfo<ExWarehouseVo> list(@Validated(QueryGroup.class) ExWarehouseBo bo, PageQuery pageQuery) {
        if(LoginHelper.getLoginUser().getRolePermission().contains("sxcangguang")){
//            params.setDeptId(iSysDeptService.selectDeptById(getLoginUser().getDeptId()).getParentId());
            bo.setStoreIds(iStoreService.selectAncestorsByUserId(LoginHelper.getUserId()));
        }
        return iExWarehouseService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出出库单列表
     */
    @ApiOperation("导出出库单列表")
    @SaCheckPermission("wms:exWarehouse:export")
    @Log(title = "出库单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Validated ExWarehouseBo bo, HttpServletResponse response) {
        List<ExWarehouseVo> list = iExWarehouseService.queryList(bo);
        ExcelUtil.exportExcel(list, "出库单", ExWarehouseVo.class, response);
    }

    /**
     * 导出出库单列表(盘点核对用)
     */
    @ApiOperation("导出出库单列表新")
    @SaCheckPermission("wms:exWarehouse:export")
    @Log(title = "出库单", businessType = BusinessType.EXPORT)
    @PostMapping("/exportOutWarehouse")
    public void exportOutWarehouse(@Validated ExWarehouseProExportBo bo, HttpServletResponse response) {
        List<ExWarehouseProExportVo> list = iExWarehouseService.getExWarehouseProExportList(bo);
        ExcelUtil.exportExcel(list, "出库记录表", ExWarehouseProExportVo.class, response);
    }

    /**
     * 获取出库单详细信息
     */
    @ApiOperation("获取出库单详细信息")
//    @SaCheckPermission("wms:exWarehouse:query")
    @GetMapping("/{id}")
    public R<ExWarehouseVo> getInfo(@ApiParam("主键")
                                     @NotNull(message = "主键不能为空")
                                     @PathVariable("id") String id) {
        ExWarehouseVo vo = iExWarehouseService.queryById(id);
        ExWarehouseDtlBo bo = new ExWarehouseDtlBo();
        bo.setWid(id);
        bo.setDelFlag("0");
        List<ExWarehouseDtlVo> items = iExWarehouseDtlService.queryList(bo);
        vo.setItems(items);
        SysOssBo oss = new SysOssBo();
        oss.setObjid(vo.getId());
        oss.setBuss("wms_exWarehouse");
        vo.setOss(iSysOssService.selectSysOssList(oss));
        if(vo.getReturnTime()!=null){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-DD-mm");
            vo.setReturnTimeNew(format.format(vo.getReturnTime()));
        }
        return R.ok(vo);
    }

    /**
     * 新增出库单
     */
    @ApiOperation("新增出库单")
    @SaCheckPermission("wms:exWarehouse:add")
    @Log(title = "出库单", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    @Transactional(rollbackFor = Exception.class)
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ExWarehouseVo vo) {
        ExWarehouseBo bo = new ExWarehouseBo();
        BeanUtil.copyProperties(vo,bo);
        return toAjax(iExWarehouseService.insertByBo(bo) != null ? 1 : 0);
    }

    /**
     * 修改出库单
     */
    @ApiOperation("修改出库单")
    @SaCheckPermission("wms:exWarehouse:edit")
    @Log(title = "出库单", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    @Transactional(rollbackFor = Exception.class)
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ExWarehouseVo vo) {
        ExWarehouseBo bo = new ExWarehouseBo();
        BeanUtil.copyProperties(vo,bo);
        return toAjax(iExWarehouseService.updateByBo(bo) != null ? 1 : 0);
    }

    /**
     * 删除出库单
     */
    @ApiOperation("删除出库单")
    @SaCheckPermission("wms:exWarehouse:remove")
    @Log(title = "出库单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> remove(@ApiParam("主键串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(iExWarehouseService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    /**
     * 删除出库单
     */
    @ApiOperation("归还出库单")
//    @SaCheckPermission("wms:exWarehouse:remove")
    @Log(title = "出库单", businessType = BusinessType.DELETE)
    @GetMapping("returnExWarehouse/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> returnExWarehouse(@ApiParam("主键串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(iExWarehouseService.returnTransfer(Arrays.asList(ids), true) ? 1 : 0);
    }

}
